杨辉三角-金字塔格式输出

该博客介绍了如何根据输入的高度,以金字塔格式输出杨辉三角的前几行。
摘要由CSDN通过智能技术生成

输入:杨辉三角的高度height

输出:以金字塔形式打印出杨辉三角的前height行

#include <stdio.h>
#include <stdlib.h>

int main(int argc,char **argv)
{
    int height;
    printf("请输入杨辉三角的高度\n");
    scanf("%d",&height);
    int **array=(int **)malloc(sizeof(int *)*height);    //动态生成二维数组
    for(int i=0;i<height;i++)
    {
          array[i]=(int *)malloc(sizeof(int)*height);
    }

    int row,col;
    for(row=0;row<height;row++)
    {
        for(col=0;col<(height-row);col++)            //填充空格,使输出为金字塔形式
        {
            printf("  ");
        }
        for(col=0;col<=row;col++)
        {
            if(col==0||row==col)
            {
                arr
杨辉三角,也称为帕斯卡三角,是一个自古以来就有的数学概念,在C语言中,你可以用循环或递归的方式来构建它。这种三角形的特点是每个数字都是它上面两个数字的和,从左上角开始,每一行的最后一个数字和倒数第二个数字都是1。 下面是使用C语言打印杨辉三角的一个简单方法: ```c #include <stdio.h> void printPascalTriangle(int n) { for (int line = 0; line < n; line++) { // 前导空格 for (int spaces = n - 1 - line; spaces > 0; spaces--) { printf(" "); } // 打印当前行的数字 for (int col = 0; col <= line; col++) { if (col == 0 || col == line) { printf("%d", 1); // 首尾数字为1 } else { printf("%d", pascal_triangle[line][col]); // 使用前一行的数字计算当前位置的值 } // 如果不是最后一列,加一个分隔符 if (col != line) { printf(" "); } } printf("\n"); // 换行 } } // 初始化杨辉三角的前一行 int pascal_triangle = {1}; // 计算并填充更大的三角形 for (int i = 1; i < n; i++) { int *new_row = (int *)malloc(sizeof(int) * (i + 1)); new_row = new_row[i] = 1; for (int j = 1; j < i; j++) { new_row[j] = pascal_triangle[i - 1][j - 1] + pascal_triangle[i - 1][j]; } // 将新行存储到数组中 for (int j = 0; j < i; j++) { pascal_triangle[i][j] = new_row[j]; } free(new_row); // 释放旧行空间 } int main() { int rows; printf("Enter the number of rows for the Pascal's triangle: "); scanf("%d", &rows); printPascalTriangle(rows); return 0; } ``` 运行这个程序时,会提示用户输入行数,然后它将打印出指定行数的杨辉三角
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值